package feed

type Entry struct {
	Id int64
	Data interface{}
}

type Feed struct {
	first int64
	last int64
	entries map[int64]Entry
	max int64
}

func New () *Feed {
	return &Feed{0, 0, make(map[int64]Entry), int64(9223372036854775800)}
}

func NewLimited (n int64) *Feed {

	return &Feed{0, 0, make(map[int64]Entry), n}
}

func (f *Feed) Post (data interface{}) {

	f.last++
	f.entries[f.last] = Entry{f.last, data}
	if f.last - f.first > f.max {
		delete(f.entries, f.first)
		f.first++
	}
}

func (f *Feed) Since (id int64, res chan Entry) {

	for i := id; i < f.last; i++ {
		res <- f.entries[i]
	}
}

/*func (f *Feed) SinceSlice(id int64) ([]Entry, bool) {

	if f.last > f.first {
		return f.entries[id:f.last], id < f.last
	} else if id > f.first {
		return append(f.entries[id:], f.entries[:f.last]), true
	} else if id < f.first {
		return f.entries[id:f.last], true
	} else {
		return nil, false
	}
}*/

func (f *Feed) Iter() (res chan Entry) {

	for i := f.first; i < f.last; i++ {
		res <- f.entries[i]
	}

	return
}

func (f *Feed) Tail() (interface{}) {
	return f.entries[f.last].Data
}

func (f *Feed) Head() (interface{}) {
	return f.entries[f.first].Data
}
